setError(e.toString());

});

}

In login, we call TodoDataService’s login method which calls the Django API login endpoint:

Analyze Code

login(data){

return axios.post("http://localhost:8000/api/login/", data);

}

The login API returns an authorization token which we set to the token state variable, setToken(response.data.token) .

Analyze Code

localStorage.setItem('token', response.data.token);

localStorage.setItem('user', user.username);

Additionally, we store the token and username in local storage so that a user will not have to constantly re-login as

she navigates away and returns to our application. Appreciate that with tokens, we do not need to store or pass the

user password around.

Analyze Code

.catch( e =>{

console.log('login', e);

setError(e.toString());

});

If there are any errors, we store them in the error state variable.

So, from the Login component, we call the login function in App.js and set App’s user state. If necessary, we can

pass on the logged-in user to other components e.g. AddTodo, TodosList.

/component/login.js

Analyze Code

const login = () => {

props.login({username: username, password: password});

props.history.push('/');

}

After login, we redirect to the main page with props.history.push('/').

CORS

Before running and testing our app, we have to deal with Cross-Origin Resource Sharing (CORS). there are

potential security issues when a frontend interacts with a backend API hosted on a different domain or port, e.g.

localhost:3000 and localhost:8000. The server thus has to use the django-cors-headers middleware to include

specific HTTP headers to allow the client to determine if cross-domain requests are permitted.

To install django-cors-headers, run the command:

Execute in Terminal

pip3 install django-cors-headers[DCB8]

To add django-cors-headers to our project, in todobackend/backend/settings.py, add the following codes in bold:

Modify Bold Code

INSTALLED_APPS = [

'api',

'rest_framework.authtoken',

'corsheaders',

]

MIDDLEWARE = [

'django.contrib.messages.middleware.MessageMiddleware',

'django.middleware.clickjacking.XFrameOptionsMiddleware',

'corsheaders.middleware.CorsMiddleware',

]